package com.aode.utils.sharedhelper;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.aode.common.bean.response.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

public class SharedHelperBean {
    private static final String PREF_NAME_DEFAULT = "LocalModelCache";

    /**
     * 从本地SP中读取对象
     * @param context
     * @param t
     * @param preferenceId
     * @param <T>
     */
    public static <T> void saveObj2SP(Context context,T t,String preferenceId){
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME_DEFAULT,Context.MODE_PRIVATE);
        ByteArrayOutputStream bos;
        ObjectOutputStream oos = null;
       try {
           bos = new ByteArrayOutputStream();
           oos = new ObjectOutputStream(bos);
           oos.writeObject(t);
           byte[] bytes = bos.toByteArray();
           String ObjStr = Base64.encodeToString(bytes,Base64.DEFAULT);
           SharedPreferences.Editor editor = preferences.edit();
           editor.putString(preferenceId,ObjStr);
           editor.commit();
       }catch (IOException e){
           e.printStackTrace();
       }finally {
           if(oos!=null){
               try {
                   oos.flush();
                   oos.close();
               }catch (IOException e){
                   e.printStackTrace();
               }

           }
       }
   }

    /**
     * 从本地sp中读取对象
     * @param context
     * @param preferenceId
     * @param <T>
     * @return
     */
    public static <T extends Object> T getObjFromSP(Context context,String preferenceId){
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME_DEFAULT,Context.MODE_PRIVATE);
        byte[] bytes = Base64.decode(preferences.getString(preferenceId,""),Base64.DEFAULT);
        ByteArrayInputStream bis;
        ObjectInputStream ois = null;
        T obj = null;
        try {
            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            obj = (T)ois.readObject();
        }catch ( Exception e){
            e.printStackTrace();
        }finally {
            if(ois!=null){
                try {
                    ois.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return obj;
    }

    /**
     * 清除暂存数据
     * @param context
     * @param preferenceId
     */
    public static void clean(Context context,String preferenceId){
        SharedPreferences preferences =context.getSharedPreferences(PREF_NAME_DEFAULT,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear().commit();
    }
}
